<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionsController extends Controller
{

    public function __construct()
    {
        // 只让未登录用户访问登录页面
        $this->middleware('guest', [
            'only' => ['create']
        ]);
    }

    // 登录页面
    public function create() {
        return view('sessions.create');
    }

    // 登录操作
    public function store(Request $request) {
        $credentials = $this->validate($request, [
            'email' => 'required|email|max:255',
            'password' => 'required'
        ]);

//        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
//        }
        if (Auth::attempt($credentials, $request->has('remember'))) {
            if (Auth::user()->activated) {
                session()->flash('success', '欢迎回来~');
                $fallback = route('users.show', [Auth::user()]);

                // intended方法可将页面重定向到上一次请求尝试访问的页面
                return redirect()->intended($fallback);
            } else {
                Auth::logout();
                session()->flash('warning', '您的账号未激活，请检查邮箱中的注册邮件进行激活');
                return redirect('/');
            }

        } else {
            session()->flash('danger', '很抱歉，您的邮箱和密码不匹配');
            return redirect()->back()->withInput();
        }

    }

    // 退出
    public function destroy() {
        Auth::logout();
        session()->flash('success', '您已退出！');
        return redirect('login');
    }
}
